<template>
  <div class="wrapper">
    <div class="main">
      <div class="search-bar">
        <el-input v-model="searchPost.productId" placeholder="请输入产品编号" clearable style="width: 220px; margin-right: 20px;"></el-input>
        <el-input v-model="searchPost.productName" placeholder="请输入产品名称" clearable style="width: 220px; margin-right: 20px;"></el-input>
        <div class="btn-group">
          <el-button type="primary" size="mini" @click="getProductList(true)">查询</el-button>
        </div>
      </div>
      <div class="table">
        <el-table :height="tableHeight+'px'" :data="tableData" @selection-change="handleSelectionChange" border style="width: 100%">
          <el-table-column
            type="selection"
            align="center"
            width="55">
          </el-table-column>
          <el-table-column label="序号" align="center" width="80">
            <template slot-scope="scope">{{scope.$index+1}}</template>
          </el-table-column>
          <el-table-column prop="productId" label="产品编号" align="center" min-width="150"></el-table-column>
          <el-table-column prop="productOldId" label="旧产品编号" align="center" min-width="150"></el-table-column>
          <el-table-column prop="productName" label="产品名称" align="center" min-width="150"></el-table-column>
          <el-table-column label="操作" align="center" min-width="100">
            <template slot-scope="scope">
              <el-button @click.native.prevent="openEditDialog(scope)" :disabled="!hasAuthority" type="text" size="small">编辑</el-button>
              <el-button @click.native.prevent="delProduct(scope.row)" :disabled="!hasAuthority" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="bottom">
        <div class="btn-wrapper">
          <el-button type="primary" size="mini" @click="openEditDialog" :disabled="!hasAuthority">新增</el-button>
          <el-button type="primary" size="mini" @click="delAll" :disabled="multipleSelection.length === 0 || !hasAuthority">批量删除</el-button>
          <el-button type="primary" size="mini" @click="$refs.uploadInput.click()" :disabled="!hasAuthority">批量导入</el-button>
          <input ref="uploadInput" type="file" style="display: none;" @change="uploadFile($event)">
          <el-button type="primary" size="mini" @click="exportProduct">导出产品模板</el-button>
        </div>
        <el-pagination background layout="prev, pager, next" :total="pageConfig.totalCount" :page-size="pageConfig.pageSize" :current-page.sync="pageConfig.pageIndex" @current-change="currentChangeHandle"></el-pagination>
      </div>
    </div>
    <el-dialog :title="!form.id ? '新增产品' : '编辑产品'" :visible.sync="dialogVisible" width="600px">
      <el-form label-width="100px" label-position="left">
        <el-form-item label="产品编号">
          <span style="color: red; position:absolute; left: -110px;">*</span>
          <el-input v-model="form.productId" placeholder="请输入产品编号" :disabled="!!form.id"></el-input>
        </el-form-item>
        <el-form-item label="产品名称">
          <span style="color: red; position:absolute; left: -110px;">*</span>
          <el-input v-model="form.productName" placeholder="请输入产品名称"></el-input>
        </el-form-item>
        <el-form-item label="旧产品编号">
          <el-input v-model="form.productOldId" placeholder="请输入旧产品编号"></el-input>
        </el-form-item>
        <el-form-item label="旧产品名称">
          <el-input v-model="form.productOldName" placeholder="请输入旧产品名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" style="display: flex; justify-content: space-between;">
        <div>
          <!-- <el-button @click="delProduct(false)" size="mini" v-if="form.id">删除</el-button> -->
        </div>
        <div>
          <el-button @click="dialogVisible = false" size="mini">取消</el-button>
          <el-button type="primary" @click="submitForm" size="mini">提交</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import formUtil from '@/utils/formUtil'
export default {
  name: '',
  data () {
    return {
      searchPost: {
        productId: '',
        productName: ''
      },
      tableHeight: '',
      dialogVisible: false,
      pageConfig:{
        pageIndex: 1,
        pageSize: 15,
        totalCount: 0
      },
      tableData: [],
      form: {
        productId: '',
        productName: '',
        productOldId: '',
        productOldName: '',
      },
      multipleSelection: [],
      authorityAsd: {},
    };
  },
  components: {},
  mounted () {
    this.tableHeight = document.documentElement['clientHeight'] - 200
    window.onresize = () => {
      this.tableHeight = document.documentElement['clientHeight'] - 200
    }
    this.getAuthorityAsd();
    this.getProductList(true)
  },
  computed: {
    hasAuthority() {
      return this.authorityAsd.userLevel === '1'
    }
  },
  methods: {
    async getAuthorityAsd() {
      this.authorityAsd = await this.$httpN.postB('pc/authority/asd')
    },
    async getProductList(type) {
      if(type) this.pageConfig.pageIndex = 1
      let {list, totalCount} = await this.$httpN.postB('pc/product/list',{
        page: this.pageConfig.pageIndex,
        limit: this.pageConfig.pageSize,
        productId: this.searchPost.productId,
        productName: this.searchPost.productName
      });
      this.tableData = list
      if(type) this.pageConfig.totalCount = totalCount
    },
    currentChangeHandle (val) {
      this.pageConfig.pageIndex = val
      this.getProductList()
    },
    openEditDialog(data) {
      formUtil.resetData(this.form);
      if(data.row) this.form = JSON.parse(JSON.stringify(data.row))
      this.dialogVisible = true;
    },
    async submitForm() {
      if(!this.form.productId) return this.$message.error('请输入产品编号');
      if(!this.form.productName) return this.$message.error('请输入产品名称');
      var data = {
        productId: this.form.productId,
        productName: this.form.productName,
        productOldId: this.form.productOldId,
        productOldName: this.form.productOldName
      }
      if(this.form.id) data.id = this.form.id
      if(!await this.$httpN.postB(!this.form.id ? 'pc/product/save' : 'pc/product/update', data)) return
      formUtil.submitSuccess('保存成功');
      this.getProductList(true);
      this.dialogVisible = false;
    },
    async delProduct(data) {
      let id = data ? data.id : this.form.id;
      formUtil.submitConfirm('请问您是否确定删除该产品？', async ()=> {
        if(!await this.$httpN.postB('pc/product/delete', {ids: id})) return;
        formUtil.submitSuccess('删除成功');
        this.getProductList(true);
        this.dialogVisible = false;
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async delAll() {
      let ids = this.multipleSelection.map(item => item.id);
      formUtil.submitConfirm('请问您是否确定删除该产品？', async ()=> {
        if(!await this.$httpN.postB('pc/product/delete', {ids: ids.join(',')})) return;
        formUtil.submitSuccess('删除成功');
        this.getProductList(true);
      })
    },
    async exportProduct() {
      let fileData = await this.$httpN.get('pc/product/templateExport', {}, 'blob');
      this.downFile(fileData, '产品模板.xls');
    },
    downFile(blob, fileName) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
      }
    },
    uploadFile(e) {
      let file = e.target.files[0];
      var formData = new FormData();
      formData.append("file", file);
      formData.append("name", 'file');
      this.$httpN.upload('pc/product/fileUpload', formData).then((res) => {
        if(res.status === 200 && res.data.code === 0) {
          formUtil.submitSuccess('上传成功')
          this.getProductList(true);
          if(res.data.data.failData) return this.$alert('编号为"' + res.data.data.failData + '"的产品已存在，请更换编号再导入', '注意')
        }else{
          this.$message.error('上传文件出错,请重试')
        }
      })
      e.target.value = '';
    }
  }
}
</script>

<style lang='scss' scoped>
.wrapper {
  height: 100%;
  width: 100%;
  padding: 0 15px;
  .main {
    height: 100%;
    padding: 15px 0;
    .search-bar {
      padding-bottom: 15px;
      display: flex;
      .btn-group {
        margin-left: 10px;
        line-height: 36px;
      }
    }
    .table {
      height: calc(100% - 93px);
      overflow: auto;
    }
    .bottom {
      height: 54px;
      padding: 13px 0;
      display: flex;
      justify-content: space-between;
      .btn-wrapper {
        white-space: nowrap;
        overflow-x: auto;
        overflow-y: hidden;
        &::-webkit-scrollbar {
          width: 4px;
          height: 4px;
        }
        &::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
          border-radius: 5px;
          background: rgba(0,0,0,0.2);
          scrollbar-arrow-color:red;
        }
        &::-webkit-scrollbar-track {/*滚动条里面轨道*/
          border-radius: 0;
          background: rgba(0,0,0,0.1);
        }
      }
    }
  }
}
</style>